package com.qianjiangcloud.store.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.libary.cache.MyImageLoader;
import cn.shopex.multiimagepreview.app.GalleryActivity;
import cn.shopex.multiimagepreview.app.GiftBean;


/**
 * Created by Jelly on 2016/8/1.
 */
public class AccountAfterSalesDetailsFragment extends BaseDoFragment implements View.OnClickListener {
    private String orderId=null;
    private LayoutInflater mInflate;
    private TextView mOrderId;
    private ListView mGoodList;
    private LinearLayout mReturnReason;
    private ImageView mDocument1;
    private ImageView mDocument2;
    private ImageView mDocument3;
    private OrderStatueChildAdapter mAdapter;
    private DecimalFormat mDecimalFormat = new DecimalFormat("0.00");
    private ArrayList<GiftBean> list;

    @Override
    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mActionBar.setTitle(R.string.after_sales_details);
        mInflate=inflater;
        rootView=inflater.inflate(R.layout.fragment_after_sales_details,null);
        mOrderId= (TextView) findViewById(R.id.order_id);
        mGoodList= (ListView) findViewById(R.id.goods_list);
        mReturnReason= (LinearLayout) findViewById(R.id.return_reason);
        mDocument1= (ImageView) findViewById(R.id.evidence1);
        mDocument2= (ImageView) findViewById(R.id.evidence2);
        mDocument3= (ImageView) findViewById(R.id.evidence3);
        mDocument1.setOnClickListener(this);
        mDocument2.setOnClickListener(this);
        mDocument3.setOnClickListener(this);
        Run.excuteJsonTask(new JsonTask(),new GetAfterDetailsTask());

    }

    @Override
    public void onClick(View v) {
        if (v==mDocument1||v==mDocument2||v==mDocument3) {
            ImageView view = (ImageView) v;
            int position = (int) view.getTag();

            Intent intent = new Intent(getActivity(), GalleryActivity.class);
            intent.putExtra("position", position);
            intent.putExtra("Extra_List", list);
            startActivity(intent);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setTitle(R.string.after_sales_details);
        Intent intent=mActivity.getIntent();
        if (intent!=null) {
            orderId = intent.getStringExtra("orderId");
        }
    }
    public void addConversationView(JSONObject object){
        View view=mInflate.inflate(R.layout.fragment_after_sales_detalis_conver_item,null);
        TextView type= (TextView) view.findViewById(R.id.conver_type);
        TextView content= (TextView) view.findViewById(R.id.conver_content);
        content.setText(object.optString("conversation_content"));
        if (!object.optString("conversation_content").equals("")) {
            if (object.optInt("conversation_type") == 0) {
                type.setText("系统:");
                type.setTextColor(getResources().getColor(R.color.red));
                content.setTextColor(getResources().getColor(R.color.red));

            } else {
                type.setText("用户:");
                type.setTextColor(getResources().getColor(R.color.after_conversation_type));
                content.setTextColor(getResources().getColor(R.color.after_conversation_type));
            }
            mReturnReason.addView(view);
        }

    }
    private class OrderStatueChildAdapter extends BaseAdapter {
        private ViewHolder mHolder;
        public List<JSONObject> mShoppLists = new ArrayList<JSONObject>();

        public OrderStatueChildAdapter(JSONArray json) {
            try {
                if (json != null && json.length() > 0) {
                    this.mShoppLists.clear();
                    for (int i = 0; i < json.length(); i++) {
                        this.mShoppLists.add(json.getJSONObject(i));
                    }
                }
            } catch (Exception e) {
            }
        }

        @Override
        public int getCount() {
            return mShoppLists.size();
        }

        @Override
        public Object getItem(int position) {
            return mShoppLists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                mHolder = new ViewHolder();
                convertView = View.inflate(mActivity, R.layout.item_order_statue_child, null);
                mHolder.mShoppIconIV = (ImageView) convertView.findViewById(R.id.order_iv_shopp_icon);
                mHolder.mShoppNameTV = (TextView) convertView.findViewById(R.id.order_tv_shopp_name);
                mHolder.mShoppTotalPrice = (TextView) convertView.findViewById(R.id.order_tv_shopp_total_price);
                mHolder.mShoppNumberTV = (TextView) convertView.findViewById(R.id.order_tv_shopp_number);
                mHolder.mLayout = (LinearLayout) convertView.findViewById(R.id.order_statue_ll);
                mHolder.shopInfo= (TextView) convertView.findViewById(R.id.order_tv_shopp_info);
                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }

            JSONObject mJsonObject = mShoppLists.get(position);
            JSONObject product = mJsonObject.optJSONObject("products");
            mHolder.mLayout.setTag(product);

            if (position >= mShoppLists.size() - 1) {
                ((View) convertView.findViewById(R.id.order_view)).setVisibility(View.GONE);
            } else {
                ((View) convertView.findViewById(R.id.order_view)).setVisibility(View.VISIBLE);
            }

            MyImageLoader.displayDefaultImage(mJsonObject.optString("thumbnail_pic_src"),mHolder.mShoppIconIV);
            mHolder.mShoppNameTV.setText(mJsonObject.optString("name"));
            mHolder.mShoppTotalPrice.setText(mActivity.getString(R.string.shopping_car_price,
                    mDecimalFormat.format(mJsonObject.optDouble("price") * mJsonObject.optInt("quantity"))));
            mHolder.mShoppTotalPrice.setTextColor(getResources().getColor(R.color.red));
            mHolder.mShoppNumberTV.setText("x " + mJsonObject.optString("quantity"));
            mHolder.mShoppNumberTV.setPadding(0,5,20,0);
            JSONObject projects=mJsonObject.optJSONObject("products");
//            if (!projects.isNull("spec_info"))
//            mHolder.shopInfo.setText(projects.optString("spec_info"));
            return convertView;
        }

        private class ViewHolder {
            public LinearLayout mLayout;
            public ImageView mShoppIconIV;
            public TextView mShoppNameTV, mShoppTotalPrice, mShoppNumberTV,shopInfo;
        }


    }


    private class GetAfterDetailsTask implements JsonTaskHandler {


        @Override
        public void task_response(String json_str) {
            hideLoadingDialog();
            try {
                JSONObject all = new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    JSONObject data=all.optJSONObject("data");
                    mOrderId.setText(data.optString("order_id"));
                    JSONObject evidence=data.optJSONObject("evidence");
                    if (evidence!=null) {
                        String evidence1 = evidence.optString("evidence1");
                        String evidence2 = evidence.optString("evidence2");
                        String evidence3 = evidence.optString("evidence3");
                        list = new ArrayList<>();
                        if(evidence1.length()>0)
                            list.add(new GiftBean(evidence1));

                        if(evidence2.length()>0)
                            list.add(new GiftBean(evidence2));

                        if(evidence3.length()>0)
                            list.add(new GiftBean(evidence3));

                        if (evidence1 != null && !TextUtils.isEmpty(evidence1)) {
                            MyImageLoader.displayDefaultImage(evidence1,mDocument1);
                            mDocument1.setTag(0);
                            mDocument1.setVisibility(View.VISIBLE);
                        }
                        if (evidence2 != null && !TextUtils.isEmpty(evidence2)) {
                            MyImageLoader.displayDefaultImage(evidence2,mDocument2);
                            mDocument2.setVisibility(View.VISIBLE);
                            mDocument2.setTag(1);
                        }
                        if (evidence3 != null && !TextUtils.isEmpty(evidence3)) {
                            MyImageLoader.displayDefaultImage(evidence3,mDocument3);
                            mDocument3.setVisibility(View.VISIBLE);
                            mDocument3.setTag(2);
                        }
                    }
                    JSONArray converArray=data.optJSONArray("conversation");
                    mReturnReason.removeAllViews();
                    if (converArray==null||converArray.length()==0){
                        mReturnReason.setVisibility(View.GONE);
                    } else {
                        for (int i = 0; i < converArray.length(); i++) {
                            JSONObject object = converArray.optJSONObject(i);
                            addConversationView(object);
                        }
                        if (mReturnReason.getChildCount()>0){
                            mReturnReason.setVisibility(View.VISIBLE);
                        } else {
                            mReturnReason.setVisibility(View.GONE);
                        }

                    }
                    JSONArray item=data.getJSONArray("items");
                    mGoodList.setAdapter(new OrderStatueChildAdapter(item));

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }

        @Override
        public JsonRequestBean task_request() {
            showCancelableLoadingDialog();
            JsonRequestBean req=new JsonRequestBean("mobileapi.aftersales.details");
            req.addParams("return_id",orderId);
            return req;
        }
    }
}
